package com.example.waternetwork.api.config;

import com.example.waternetwork.api.system.entity.LoginUser;
import com.example.waternetwork.api.utils.JwtUtils;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Value("${server.servlet.context-path:/}")
    private String contextPath;


    private final JwtUtils jwtUtils;

    public JwtFilter(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {


        if (request.getRequestURI().startsWith(contextPath + "/v3/api-docs")
                || request.getRequestURI().startsWith(contextPath + "/swagger-ui")
                || request.getRequestURI().startsWith(contextPath + "/swagger-resources")
                || request.getRequestURI().startsWith(contextPath + "/webjars")
                || request.getRequestURI().equals(contextPath + "/system/auth/login")) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = extractToken(request);
        if (token != null) {
            String username = validateToken(token);
            String name = jwtUtils.parseName(token);
            Long id = jwtUtils.parseId(token);
            LoginUser userDetails = new LoginUser(id,username, name, Collections.emptyList());
            Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(auth);
            filterChain.doFilter(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "无效的 Token");
        }
    }

    // 提取 Bearer Token
    private String extractToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }

    // 验证 Token 是否有效
    private String  validateToken(String token) {
        try {
            return jwtUtils.parseToken(token);
        } catch (JwtException e) {
            return null ;
        }
    }

}
